package com.gdsz.libbasic.utils.file

import android.content.Context

object SharedPreferencesUtils {
    /**
     * 保存在手机里面的文件名
     */
    private const val FILE_NAME = "share_date"

    /**
     * 保存数据的方法，我们需要拿到保存数据的具体类型，然后根据类型调用不同的保存方法
     *
     * @param key
     * @param data
     */
    fun setParam(context: Context, key: String?, data: Any) {
        val type = data.javaClass.simpleName
        val sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
        val editor = sp.edit()
        when (type) {
            "String" -> editor.putString(key, data as String)
            "Integer" -> editor.putInt(key, (data as Int))
            "Boolean" -> editor.putBoolean(key, (data as Boolean))
            "Float" -> editor.putFloat(key, (data as Float))
            "Long" -> editor.putLong(key, (data as Long))
        }
        editor.apply()
    }

    /**
     * 得到保存数据的方法，我们根据默认值得到保存的数据的具体类型，然后调用相对于的方法获取值
     *
     * @param key
     * @param data
     * @return
     */
    fun getParam(context: Context, key: String?, data: Any): Any? {
        val type = data.javaClass.simpleName
        val sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
        if ("String" == type) {
            return sp.getString(key, data as String)
        } else if ("Integer" == type) {
            return sp.getInt(key, (data as Int))
        } else if ("Boolean" == type) {
            return sp.getBoolean(key, (data as Boolean))
        } else if ("Float" == type) {
            return sp.getFloat(key, (data as Float))
        } else if ("Long" == type) {
            return sp.getLong(key, (data as Long))
        }
        return null
    }

    /**
     * 清除所有数据
     *
     */
    fun clearAll(context: Context) {
        val sp = context.getSharedPreferences(
            FILE_NAME,
            Context.MODE_PRIVATE
        )
        val editor = sp.edit()
        editor.clear().apply()
    }

    fun clear(context: Context, key: String?) {
        val sp = context.getSharedPreferences(
            FILE_NAME,
            Context.MODE_PRIVATE
        )
        val editor = sp.edit()
        editor.remove(key)
        editor.apply()
    }
}